
lib.use(['element', 'table', 'form','authtree'], function () {
    var layer = layui.layer;
    var form = layui.form;
    var $ = layui.jquery;
    var updateForm = layui.Form('fromForm');
    var authtree = layui.authtree;
    var reqUrl;
     form.verify({
            roleName: function(value, item){ //value：表单的值、item：表单的DOM对象
                if(!value){
                    return '角色名称不能为空';
                }
                if(!new RegExp("^[a-zA-Z0-9_\u4e00-\u9fa5\\s·]+$").test(value)){
                    return '角色名称不能有特殊字符';
                }
                if(/(^\_)|(\__)|(\_+$)/.test(value)){
                    return '角色名称首尾不能出现下划线\'_\'';
                }
                if(/^\d+\d+\d$/.test(value)){
                    return '角色名称不能全为数字';
                }
            }
     });
     form.on('submit(formSubmitFilter)', function (data) {
            var checked = authtree.getChecked('#LAY-auth-tree-index');
            var param = updateForm.getData();
            param.menuIdList=checked;
            console.log('Role Save param is', param);
            common.ajax.post(reqUrl, param, function (resp) {
                layer.alert('修改成功', function () {
                    location.href = 'roleList.html';
                })
            })
            return false;
     });


    function loadFormData() {
        var id = common.util.getParam('id');
        if (!id) {
            layer.alert('id错误');
            return;
        }
        common.ajax.get('/sys/role/info/'+id, {}, function (resp) {
            updateForm.setData(resp.role);
            loadRoleMenu(resp.role.menuIdList);

        });
    }

    function loadRoleMenu(menuIdList) {
        console.log('menuIdList  param is', menuIdList);
        common.ajax.get('/sys/menu/tenant-list', {}, function (resp) {
            var trees = authtree.listConvert(resp.data, {
                primaryKey: 'id'
                ,startPid: 0
                ,parentKey: 'parentId'
                ,nameKey: 'name'
                ,valueKey: 'id'
                ,checkedKey: menuIdList
            });
            // 如果后台返回的不是树结构，请使用 authtree.listConvert 转换
            authtree.render('#LAY-auth-tree-index', trees, {
                inputname: 'authids[]',
                layfilter: 'lay-check-auth',
                //prefixChildStr:'├──',
                autowidth: true,
                //openall: true
            });
            authtree.closeAll('#LAY-auth-tree-index')
            authtree.showDept('#LAY-auth-tree-index',2);
        });
    }
    (function () {

        if(common.util.getParam('id')){
            //修改
            loadFormData();
            reqUrl="/sys/role/update";
        }else{
            //新增
            reqUrl="/sys/role/save";
            loadRoleMenu([]);
            updateForm.setData({isValid:1});

        }
    })();
});
